import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';

@Injectable()
export class CookiesService {
  constructor(private readonly prismaServer: PrismaService) {}

  async uploadFile(
    file: Express.Multer.File,
    platformId: number,
    name: string,
  ) {
    if (!file) {
      throw new BadRequestException('No file uploaded');
    }
    if (!platformId) {
      throw new BadRequestException('platformId is required');
    }

    const platformExists = await this.prismaServer.platform.findUnique({
      where: { id: platformId },
    });
    if (!platformExists) {
      throw new BadRequestException(`Platform with ID ${platformId} not found`);
    }

    const savedFile = await this.prismaServer.cookie.create({
      data: {
        name,
        filename: file.originalname,
        content: file.buffer.toString('utf-8'),
        platformId,
      },
    });

    return {
      success: true,
      message: 'File uploaded successfully',
      fileId: savedFile.id,
    };
  }

  async deleteCookie(cookieId: number) {
    try {
      const deletedCookie = await this.prismaServer.cookie.delete({
        where: { id: cookieId },
      });
      return {
        success: true,
        message: `Cookie ${cookieId} deleted successfully`,
        data: deletedCookie,
      };
    } catch (error) {
      throw new Error(`Failed to delete cookie ${cookieId}: ${error.message}`);
    }
  }

  async getCookieWithPlatformName(cookieId: number) {
    const cookie = await this.prismaServer.cookie.findUnique({
      where: { id: cookieId },
      select: {
        id: true,
        name: true,
        filename: true,
        content: true,
        platformId: true,
        createdAt: true,
        platform: {
          select: { name: true }, // Only fetch platform.name
        },
      },
    });

    if (!cookie) {
      throw new Error(`Cookie with ID ${cookieId} not found`);
    }

    return {
      id: cookie.id,
      name: cookie.name,
      filename: cookie.name,
      content: cookie.content,
      platformId: cookie.platformId,
      platformName: cookie.platform.name,
      createdAt: cookie.createdAt,
    };
  }
  async getAllCookieWithPlatformName() {
    const cookies = await this.prismaServer.cookie.findMany({
      select: {
        id: true,
        name: true,
        filename: true,
        content: true,
        platformId: true,
        createdAt: true,
        platform: {
          select: { name: true }, // Only fetch platform.name
        },
      },
    });

    if (cookies.length === 0) {
      return [];
    }
    return cookies.map((cookie) => {
      return {
        id: cookie.id,
        name: cookie.name,
        filename: cookie.filename,
        content: cookie.content,
        platformId: cookie.platformId,
        platformName: cookie.platform.name,
        createdAt: cookie.createdAt,
      };
    });
  }
}
